package pers.sloera.leetcode.editor.cn;

import cn.hutool.core.lang.Assert;

import java.util.Arrays;

/**
 * 递减元素使数组呈锯齿状
 *
 * @author sloera
 * @date 2023-02-27 22:36:18
 */
class DecreaseElementsToMakeArrayZigzag {
    public static void main(String[] args) {
        Solution solution = new DecreaseElementsToMakeArrayZigzag().new Solution();
        int ret = solution.movesToMakeZigzag(new int[]{1, 2, 3});
        System.out.println(ret);
        Assert.isTrue(ret == 2);
        ret = solution.movesToMakeZigzag(new int[]{9, 6, 1, 6, 2});
        System.out.println(ret);
        Assert.isTrue(ret == 4);
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public int movesToMakeZigzag(int[] nums) {
            //  分别计算 偶和奇 两种情况
            return Math.min(minOdd(Arrays.copyOf(nums, nums.length)), minEven(Arrays.copyOf(nums, nums.length)));
        }

        private int minEven(int[] nums) {
            int count = 0;
            for (int i = 0; i < nums.length; i = i + 2) {
                count += getDiff(nums, i);
            }
            return count;
        }

        private int minOdd(int[] nums) {
            int count = 0;
            for (int i = 1; i < nums.length; i = i + 2) {
                count += getDiff(nums, i);
            }
            return count;
        }

        // 分别计算左右两边需要相加的次数
        private int getDiff(int[] nums, int current) {
            int count = 0;
            int left = current - 1;
            if (left >= 0) {
                count += getDiff(nums, current, left);
            }
            int right = current + 1;
            if (right < nums.length) {
                count += getDiff(nums, current, right);
            }
            return count;
        }

        // 偶和奇都是当前数比左右两边的大 如果 前面的满足条件，在计算右面的时候，把neighbour减小，那之前的左边条件肯定也是满足的
        private int getDiff(int[] nums, int current, int neighbour) {
            if (nums[current] <= nums[neighbour]) {
                int diff = nums[neighbour] - nums[current] + 1;
                nums[neighbour] -= diff;
                return diff;
            }
            return 0;
        }
    }
    //leetcode submit region end(Prohibit modification and deletion)

}
